#!/usr/bin/env node
/**
 * 修正版本的 Playwright MCP 服务器
 * 基于正确的 MCP 协议实现
 */

import http from 'http';
import { createConnection } from '@playwright/mcp';
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';

class FixedPlaywrightMCPServer {
  constructor(port = 3000) {
    this.port = port;
    self.server = null;
    this.mcpConnection = null;
  }

  async start() {
    this.server = http.createServer(async (req, res) => {
      // 设置 CORS 头
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
      res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

      if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
      }

      // 健康检查端点
      if (req.url === '/health') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ 
          status: 'healthy', 
          timestamp: new Date().toISOString(),
          mcp_connection: this.mcpConnection ? 'connected' : 'disconnected'
        }));
        return;
      }

      // MCP SSE 端点
      if (req.url === '/messages') {
        try {
          console.log('🔗 建立新的 MCP SSE 连接');
          
          // 创建 Playwright MCP 连接
          if (!this.mcpConnection) {
            this.mcpConnection = await createConnection({
              browser: {
                launchOptions: {
                  headless: false, // 开发时设为 false
                  args: [
                    '--no-sandbox',
                    '--disable-setuid-sandbox',
                    '--disable-blink-features=AutomationControlled'
                  ]
                }
              }
            });
            console.log('✅ Playwright MCP 连接已创建');
          }

          // 创建 SSE 传输
          const transport = new SSEServerTransport('/messages', res);
          
          // 连接 MCP
          await this.mcpConnection.connect(transport);
          console.log('✅ MCP SSE 传输已建立');
          
          // 处理连接关闭
          req.on('close', () => {
            console.log('🔌 SSE 连接关闭');
          });

          req.on('error', (error) => {
            console.error('❌ SSE 连接错误:', error);
          });

        } catch (error) {
          console.error('❌ MCP SSE 连接失败:', error);
          res.writeHead(500, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ 
            error: 'MCP connection failed', 
            details: error.message 
          }));
        }
        return;
      }

      // JSON-RPC 端点（如果需要的话）
      if (req.url === '/jsonrpc' && req.method === 'POST') {
        let body = '';
        
        req.on('data', chunk => {
          body += chunk.toString();
        });

        req.on('end', async () => {
          try {
            const jsonrpcRequest = JSON.parse(body);
            console.log('📨 收到 JSON-RPC 请求:', jsonrpcRequest);
            
            // 这里需要将 JSON-RPC 请求转换为 MCP 调用
            // 但是由于 MCP 是通过 SSE 工作的，这种方式可能不适用
            
            res.writeHead(501, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({
              jsonrpc: "2.0",
              id: jsonrpcRequest.id,
              error: {
                code: -32601,
                message: "Method not implemented. Use SSE endpoint /messages instead."
              }
            }));
            
          } catch (error) {
            console.error('❌ JSON-RPC 处理错误:', error);
            res.writeHead(400, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({
              jsonrpc: "2.0",
              id: null,
              error: {
                code: -32700,
                message: "Parse error"
              }
            }));
          }
        });
        return;
      }

      // 404 处理
      res.writeHead(404, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ 
        error: 'Not Found',
        available_endpoints: ['/health', '/messages', '/jsonrpc']
      }));
    });

    return new Promise((resolve, reject) => {
      this.server.listen(this.port, (error) => {
        if (error) {
          reject(error);
        } else {
          console.log(`🚀 修正版 Playwright MCP 服务器启动成功`);
          console.log(`📡 服务地址: http://localhost:${this.port}`);
          console.log(`🔗 MCP SSE 端点: http://localhost:${this.port}/messages`);
          console.log(`📨 JSON-RPC 端点: http://localhost:${this.port}/jsonrpc`);
          console.log(`💓 健康检查: http://localhost:${this.port}/health`);
          console.log('');
          console.log('📖 使用说明:');
          console.log('  - MCP 客户端应该连接到 /messages 端点');
          console.log('  - 使用 Server-Sent Events (SSE) 进行通信');
          console.log('  - 遵循 JSON-RPC 2.0 + MCP 协议格式');
          resolve();
        }
      });
    });
  }

  async stop() {
    if (this.mcpConnection) {
      try {
        await this.mcpConnection.close();
        console.log('🔌 MCP 连接已关闭');
      } catch (error) {
        console.error('❌ 关闭 MCP 连接失败:', error);
      }
      this.mcpConnection = null;
    }

    if (this.server) {
      return new Promise((resolve) => {
        this.server.close(() => {
          console.log('🛑 服务器已停止');
          resolve();
        });
      });
    }
  }
}

// 启动服务器
const server = new FixedPlaywrightMCPServer(3000);

async function main() {
  try {
    await server.start();
    
    // 优雅关闭处理
    process.on('SIGINT', async () => {
      console.log('\n🛑 收到停止信号，正在关闭服务器...');
      await server.stop();
      process.exit(0);
    });
    
    process.on('SIGTERM', async () => {
      console.log('\n🛑 收到终止信号，正在关闭服务器...');
      await server.stop();
      process.exit(0);
    });
    
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
}

// 错误处理
process.on('unhandledRejection', (reason, promise) => {
  console.error('❌ 未处理的 Promise 拒绝:', reason);
});

process.on('uncaughtException', (error) => {
  console.error('❌ 未捕获的异常:', error);
  process.exit(1);
});

main();
